home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip0493.zip / FACTOR.C < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  81 lines

  1. /*
  2. ** factor.c -- print prime factorization of a number
  3. ** Ray Gardner -- 1985 -- public domain
  4. ** Modified Feb. 1989 by Thad Smith > public domain
  5. **
  6. ** This version takes numbers up to the limits of double precision.
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <math.h>
  12.  
  13. int prevfact = 0;
  14. void factor (double);
  15. void show (double, int);
  16.  
  17. void main (int argc, char *argv[])
  18. {
  19.       while ( --argc )
  20.             factor(atof(*++argv));
  21. }
  22.  
  23. void factor (double n)
  24. {
  25.       double d;
  26.       int k;
  27.  
  28.       prevfact = 0;
  29.  
  30.       d = n+1;     /* test for roundoff error */
  31.       if (n+3 != d+2)
  32.       {
  33.             printf("%0.0f is too large to process.\n", n);
  34.             return;
  35.       }
  36.       if (fmod(n,1.) != 0.0)
  37.       {
  38.             printf("%f is not an integer.\n",n);
  39.             return;
  40.       }
  41.       printf("%0.0f  ",n);
  42.       if ( n < 2. )
  43.       {
  44.             printf("is less than 2.\n");
  45.             return;
  46.       }
  47.       else if ( n > 2. )
  48.       {
  49.             d = 2;
  50.             for ( k = 0; fmod(n,d) == 0.0; k++ )
  51.                   n /= d;
  52.             if ( k )
  53.                   show(d,k);
  54.             for ( d = 3; d * d <= n; d += 2 )
  55.             {
  56.                   for ( k = 0; fmod(n,d) == 0.0; k++ )
  57.                         n /= d;
  58.                   if ( k )
  59.                         show(d,k);
  60.             }
  61.       }
  62.       if ( n > 1 )
  63.       {
  64.             if ( ! prevfact )
  65.                   printf(" is prime");
  66.             else  show(n,1);
  67.       }
  68.       printf("\n");
  69. }
  70.  
  71. void show (double d, int k)
  72. {
  73.       if ( prevfact )
  74.             printf(" * ");
  75.       else  printf(" = ");
  76.       prevfact++;
  77.       printf("%0.0f",d);
  78.       if ( k > 1 )
  79.             printf("^%d",k);
  80. }
  81.